package com.bos.web.action;
import com.bos.domian.base.Promotion;
import com.bos.service.PromotionService;
import com.bos.web.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * @author misterWei
 * @create 2018年11月20号:14点35分
 * @mailbox mynameisweiyan@gmail.com
 */
@ParentPackage("json-default")
@Actions
@Controller
@Namespace("/")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PromotionAction extends BaseAction<Promotion> {
    @Autowired
    private PromotionService promotionService;

    private File titleImgFile;
    private String titleImgFileFileName;
    private String titleImgFileContentType;

    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }

    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }

    public void setTitleImgFileContentType(String titleImgFileContentType) {
        this.titleImgFileContentType = titleImgFileContentType;
    }

    @Action(value = "promotion_save",results = {@Result(type = "redirect",location = "/pages/take_delivery/promotion.html")})
    public String promotionSave(){
        //1,创建相对于当前工程的路径
        //指定文件夹的绝对路径
        String realPath = ServletActionContext.getServletContext().getRealPath("/imagesUpload/");
        //生成图片新名称
        UUID uuid = UUID.randomUUID();
        String substring = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
       // Map<String,Object> resultImagePath = new HashMap<String,Object>();
        try {                // error       url
            //3,返回值需要     0 代表成功  还有图片地址值
            File file = new File(realPath + "/" + uuid.toString() + substring);
            FileUtils.copyFile(titleImgFile, file);
            model.setTitleImg(ServletActionContext.getRequest().getContextPath() + "/imagesUpload/"+uuid.toString() + substring);
            model.setStatus("1");
            promotionService.save(model);
        }catch (Exception e){
            e.printStackTrace();
        }
        return SUCCESS;
    }
    @Action(value = "promotion_pageQuery",results = {@Result(type = "json")})
    public String promotionPageQuery (){
        PageRequest pageRequest = new PageRequest(super.page - 1, super.rows);
        ActionContext.getContext().getValueStack().push(promotionService.promotionPageQuery(page - 1, rows));
        return SUCCESS;
    }
}

